﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Configuration;
using JLL.China.Application;
using JLL.China.Infrastructure.Services;
using JLL.China.Model;
using JLL.China.Web.Areas.Listings.Models;
using System.IO;
using JLL.China.Web.Controllers;
using JLL.China.Web.Libraries;

namespace JLL.China.Web.Areas.Listings.Controllers
{
    public class ListingController : BaseController
    {
        protected int defaultPageSize = Int32.Parse(WebConfigurationManager.AppSettings["page_size_default"]);
        public ListingController()
        {
            ViewData["AjaxPage"] = "CountItemByStatusByMoudle/";
            ViewData["Module"] = "Listings";
        }


        // Search
        public ActionResult Search(int? page)
        {

            if (Session["page_size_default"] != null)
            {
                ViewData["per-page"] = Session["page_size_default"].ToString();
                defaultPageSize = Int32.Parse(Session["page_size_default"].ToString());
            }
            else
            {
                ViewData["per-page"] = defaultPageSize;
            }
            int currentPageIndex = page.HasValue ? page.Value : 1;
            //Strore Session

            Session["pageindex"] = currentPageIndex;
            ViewData["ListStatus"] = 0;

            // Get Query Search
            var property = new JLL.China.Web.Areas.Listings.Models.ListingModel();

            //
            if (Request.QueryString["SearchAction"] != null)
            {
                if (Request.QueryString["City"] != null)
                {
                    if (Request.QueryString["City"].ToString() != "")
                    {
                        property._listingCriteria.CityID = Int32.Parse(Request.QueryString["City"]);
                        ViewData["CityID"] = Request.QueryString["City"];
                    }
                }

                if (Request.QueryString["Location"] != null)
                {
                    if (Request.QueryString["Location"].ToString() != "")
                    {
                        var LocationID = Int32.Parse(Request.QueryString["Location"]);
                        property._listingCriteria.LocationID = LocationID;
                        ViewData["LocationID"] = LocationID;
                    }
                }
                if (Request.QueryString["Subarea"] != null)
                {
                    if (Request.QueryString["Subarea"].ToString() != "")
                    {
                        var SubareaID = Int32.Parse(Request.QueryString["Subarea"]);
                        property._listingCriteria.SubAreaID = SubareaID;
                        ViewData["SubareaID"] = SubareaID;
                    }
                }

                //Country
                if (Request.QueryString["Country"] != null)
                {
                    if (Request.QueryString["Country"].ToString() != "")
                    {
                        var Country = Int32.Parse(Request.QueryString["Country"]);
                        property._listingCriteria.CountryID = Country;
                        ViewData["Country"] = Country;
                    }
                }
                //Country
                if (Request.QueryString["CityInt"] != null)
                {
                    if (Request.QueryString["CityInt"].ToString() != "")
                    {
                        var CityInt = (Request.QueryString["CityInt"]);
                        property._listingCriteria.CityName = CityInt;
                        ViewData["CityInt"] = CityInt;
                    }
                }



                //PropertyType

                //

                if (Request.QueryString["PropertyType"].ToString() != "")
                {
                    var PropertyType = Int32.Parse(Request.QueryString["PropertyType"]);
                    property._listingCriteria.PropertyTypeID = PropertyType;
                    ViewData["PropertyType"] = PropertyType;
                }
                //Property Status
                int? IdStatus = null;
                if (Request.QueryString["Status"].ToString() != "")
                {
                    IdStatus = Int32.Parse(Request.QueryString["Status"]);
                    property._listingCriteria.Status = IdStatus;
                    ViewData["Status"] = IdStatus;
                }
                //Property Classification
                if (Request.QueryString["PropertyClss"].ToString() != "")
                {
                    var PropertyClss = Request.QueryString["PropertyClss"];
                    property._listingCriteria.PropertyClassification = PropertyClss;
                    ViewData["PropertyClss"] = PropertyClss;
                }
                //Property Tenure
                if (Request.QueryString["Tenure"].ToString() != "")
                {
                    var Tenure = Request.QueryString["Tenure"];
                    property._listingCriteria.Tenure = Tenure;
                    ViewData["Tenure"] = Tenure;
                }
                //Property Keyword
                if (Request.QueryString["Keyword"].ToString() != "")
                {
                    var Keyword = Request.QueryString["Keyword"];
                    property._listingCriteria.Keyword = Keyword;
                    ViewData["Keyword"] = Keyword;
                }
                //
                string ControllerName = this.ControllerContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();
                //Project
                if( ControllerName == "Project")
                {
                    var model = property.GetProjectByStatus(IdStatus).ToPagedList(currentPageIndex, defaultPageSize);
                    ViewData["TotalRecord"] = "Found " + property.CountItems + " records";

                    return View("Search", model);
                }
                //Property
               if(ControllerName == "Property" ){
                   var model = property.GetPropertyByStatus(IdStatus).ToPagedList(currentPageIndex, defaultPageSize);
                   ViewData["TotalRecord"] = "Found " + property.CountItems + " records";

                   return View("Search", model);
               }
               //PropertyInternational
               if (ControllerName == "PropertyInternational")
               {
                   var model = property.GetPropertyInternationalByStatus(IdStatus).ToPagedList(currentPageIndex, defaultPageSize);
                   ViewData["TotalRecord"] = "Found " + property.CountItems + " records";

                   return View("Search", model);
               }
               //ProjectInternational
               if (ControllerName == "ProjectInternational")
               {
                   var model = property.GetProjectInternaltionalByStatus(IdStatus).ToPagedList(currentPageIndex, defaultPageSize);
                   ViewData["TotalRecord"] = "Found " + property.CountItems + " records";

                   return View("Search", model);
               }

               return RedirectToAction("Index");

            }
            else
            {
                ViewData["TotalRecord"] = "Results";
                var model = property.GetPropertyByStatus(8).ToPagedList(currentPageIndex, defaultPageSize);
                return View("Search", model);
            }


            //
            //

        }
        //
        

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ChangeNumOfRow(FormCollection f)
        {
            Session["page_size_default"] = f["display_show_page"].ToString();
            Session["message"] = "Changed number of row";
            return RedirectToAction("Index");
        }
        public ActionResult Step1(int? id)
        {

            if (id != null)
            { //for edit
                var model = ListingService.FindById((int)id);
                if (model != null)
                {
                    ViewData["StatusID"] = model.StatusFID;
                    ViewData["ListingID"] = id;
                    return View("Step1", model);
                }
                return RedirectToAction("Index");

            }
            else
            {
                return View("Step1");
            }

        }
        [HttpPost, ValidateInput(false)]
        public ActionResult Step1(FormCollection form)
        {
            // Two the kind
            //1.Local
            //Set default for internal
            decimal CityFID = 0;
            decimal LocaltionFID = 0;
            decimal SubAreaFID = 0;
            string CityInternational = "";
            if (form["CityInt"] != null)
            {
                CityInternational = form["CityInt"].ToString();
            }
            string IsLocal = form["IsLocal"].ToString().Trim();
            int? CountryId = null;
            if (IsLocal == "LOCAL")
            {
                CityFID = decimal.Parse(form["City"].ToString());
                LocaltionFID = decimal.Parse(form["Location"].ToString());
                if (form["Subarea"] != null)
                {
                    if (form["Subarea"].ToString() != "")
                    {
                        SubAreaFID = decimal.Parse(form["Subarea"].ToString());
                    }

                }

                //China
                CountryId = JLL.China.Web.Libraries.HelperUtility.GetIdCountry();
            }
            else
            {
                CountryId = Int32.Parse(form["Country"].ToString().Trim());
            }
            //
            decimal? valisnull = null;
            float? fnull = null;

            string FloorAreaUnit = form["FloorAreaUnit"].ToString().Trim();
            string LandAreaUnit = form["LandAreaUnit"].ToString().Trim();
            float? FloorArea_SM = null;
            float? FloorArea_SF = null;
            float? FloorArea_SY = null;
            float? LandArea_SM = null;
            float? LandArea_SF = null;
            float? LandArea_SY = null;
            //
            if (FloorAreaUnit == "sqm")
            {
                FloorArea_SM = float.Parse(form["FloorArea"].ToString().Trim());
                FloorArea_SF = float.Parse((FloorArea_SM * 10.76391).ToString());
                FloorArea_SY = float.Parse((FloorArea_SM * 1.19599).ToString());
              
            }
            if (FloorAreaUnit == "sqft")
            {
                FloorArea_SF = float.Parse(form["FloorArea"].ToString().Trim());
                FloorArea_SM = float.Parse((FloorArea_SF * 0.092903).ToString());
                FloorArea_SY = float.Parse((FloorArea_SF * 0.111111).ToString());
                
                //Gross Area
            }
            //Land Area
            //
           
            if (LandAreaUnit == "sqm")
            {
                
                if (form["LandArea"] != null)
                {
                    if(form["LandArea"].ToString()!=""){
                        LandArea_SM = float.Parse(form["LandArea"].ToString().Trim());
                        LandArea_SF = float.Parse((LandArea_SM * 10.76391).ToString());
                        LandArea_SY = float.Parse((LandArea_SM * 1.19599).ToString());
                    }
                    
                   
                }
               
                
            }
            if (LandAreaUnit == "sqft")
            {
                if (form["LandArea"] != null)
                {
                   
                    if (form["LandArea"].ToString() != "")
                    {
                        LandArea_SF = float.Parse(form["LandArea"].ToString().Trim());
                        LandArea_SM = float.Parse((LandArea_SF * 0.092903).ToString());
                        LandArea_SY = float.Parse((LandArea_SF * 0.111111).ToString());
                    }
                    
                }
                
               
                //Gross Area
            }
            //
            int ListingID = 0;
            if (form["ListingID"].ToString() != "")
            {
                ListingID = int.Parse(form["ListingID"].ToString().Trim());
            }

            float AskingPriceLocal = float.Parse(form["Price"].ToString().Trim());
            float PriceUSD = (AskingPriceLocal * JLL.China.Web.Libraries.HelperUtility.GetRateUSD());
            float PriceinRMB = (form["PriceRMB"].ToString() != "") ? float.Parse(form["PriceRMB"].ToString().Trim()) : 0;
            float PriceinRMBUSD = (PriceinRMB * JLL.China.Web.Libraries.HelperUtility.GetRateUSD());
            int ProjectNameFID = Int32.Parse(form["ProjectName"].ToString().Trim());
            string PropertyFor = form["PropertyFor"].ToString();
            int StreetNameFID = Int32.Parse(form["StreetName"].ToString().Trim());
            decimal PropertyTypeFID = decimal.Parse(form["PropertyType"].ToString().Trim());
            bool _newLaunch = (form["NewLaunch"]!=null )?true:false;
            bool _Auction = (form["Auction"]!=null) ? true : false;
            string PropertyClsssm = form["PropertyClsssm"].ToString();
            string ListingType = form["ListingType"].ToString();
            string Tenure = form["Tenure"].ToString().Trim();

            string PriceUnit = form["Priceunit"].ToString().Trim();
            string Bedroom = form["Bedroom"].ToString().Trim();
            string Bathroom = form["Bathroom"].ToString().Trim();
            int? TotalFloor = null;
            if (form["TotalFloor"].ToString()!="")
            {
                TotalFloor = Int32.Parse(form["TotalFloor"].ToString().Trim());
            }
           
            string FloorLevel = form["FloorLevel"].ToString().Trim();
            string Description = form["Description"].ToString().Trim();
            string DescriptionLocal = form["DescriptionLocal"].ToString().Trim();
            int MemberFID = Int32.Parse(form["Agents"].ToString());
            string ListingSource = form["ListingSource"].ToString().Trim();
            string HouseNumber = form["HouseNumber"].ToString().Trim();
            // 
             float? EfficiencyRate= null;
             if(form["EfficiencyRate"].ToString()!=""){
                EfficiencyRate = float.Parse(form["EfficiencyRate"].ToString());
             }
            
            var listing = new Model.Listings
            {
                ID = ListingID,
                ListingType = ListingType,
                ListingCat = ListingSource,
                ProjectNameFID = ProjectNameFID,
                PropertyFor = PropertyFor,
                StreetNameFID = StreetNameFID,
                PropertyTypeFID = PropertyTypeFID,
                PropertyClsssm = PropertyClsssm,
                CityFID = CityFID,
                LocaltionFID = LocaltionFID,
                SubAreaFID = SubAreaFID,
                Tenure = Tenure,
                AskingPriceLocal = AskingPriceLocal,
                AskingPriceUSD = PriceUSD,
                Bedroom = Bedroom,
                Bathroom = Bathroom,
                FloorAreaUnit = FloorAreaUnit,
                FloorArea_SM = FloorArea_SM,
                FloorArea_SF = FloorArea_SF,
                FloorArea_SY = FloorArea_SY,
                LandAreaUnit=LandAreaUnit,
                LandArea_SM = LandArea_SM,
                LandArea_SY = LandArea_SY,
                LandArea_SF = LandArea_SF,
                TotalFloor = TotalFloor,
                FloorLevel = FloorLevel,
                Description = Description,
                DescriptionLocal = DescriptionLocal,
                MemberFID = MemberFID,
                CountryFID = CountryId,
                PriceUnit = PriceUnit,
                NewLaunch = _newLaunch,
                PriceInRMBPerSQMLocal = PriceinRMB,
                PriceInRMBPerSQMUSD = PriceinRMBUSD,
                Auction = _Auction,
                City = CityInternational,
                HouseNumber = HouseNumber,
                EfficiencyRate = EfficiencyRate
            };
            //
         int  ListignID =  ListingService.Store(listing);
         //
        
         //
         if (form["ListingID"].ToString() == "")
         {
             //Copy Image
             string prodirid = ProjectDirectoryService.GetIdByProjectNameId(ProjectNameFID).ToString();
             string SourecPath = HttpContext.Request.MapPath("~/Media/ProjectDirectory/" + prodirid.ToString());
             string DiscPath = HttpContext.Request.MapPath("~/Media/Listings/" + ListignID.ToString());
             if (!Directory.Exists(DiscPath))
             {
                 Directory.CreateDirectory(DiscPath);
             }
             DirectoryInfo sourcedinfo = new DirectoryInfo(SourecPath);
             DirectoryInfo destinfo = new DirectoryInfo(DiscPath);

             JLL.China.Web.Libraries.HelperUtility.CopyFiles(sourcedinfo, destinfo, prodirid, ListignID.ToString());
             //
             Session["Action"] = "Create";
             Session["messageType"] = "Success";
             Session["message"] = "Create successfully.";
             return RedirectToAction("Step2/" + ListignID );
         }
         else
         {

             Session["messageType"] = "Success";
             Session["message"] = "Updated successfully.";
             return RedirectToAction("Step2/" + ListignID.ToString());

         }

        }
        public ActionResult Step2(int? id)
        {
            var model = new ListingDetailModel();
            if (id != null)
            { //for edit

                model.projectdir = ListingService.GetProjectDirDetail((int)id, 1);
                model.localprojectdir = ListingService.GetProjectDirDetail((int)id, 2);
                ViewData["ListingID"] = id.Value.ToString();

                ViewData["StatusID"] = "";
                return View("Step2", model);
            }
            else
            {
                return RedirectToAction("Index");
            }


        }
        [HttpPost, ValidateInput(false)]
        public ActionResult Step2(ListingDetailModel prodetail)
        {
            var item = prodetail.projectdir;
            item.LanguageID = 1;

            ListingService.UpdateStep2(item);

            var localitem = prodetail.localprojectdir;
            localitem.LanguageID = 2;
            localitem.SiteArea = item.SiteArea;
            ListingService.UpdateStep2(localitem);

            Session["messageType"] = "Success";
            Session["message"] = "Updated successfully.";


            return RedirectToAction("Step3/" + item.ListingFID.ToString());

        }
       
        //
        public ActionResult Step3(int? id )
        {
            if (id != null)
            {
                var model = ListingService.FindById((int)id);
                ViewData["ListingID"] = id;
                ViewData["StatusID"] = model.StatusFID;
                return View("Step3", model);
            }
            else
            {
                return RedirectToAction("Index");
            }
        }
        [HttpPost]
        public ActionResult Step3(int id, IEnumerable<int> Facilities, IEnumerable<int> Features)
        {
            //
            string _Facilities = "0";
            if (Facilities != null)
            {
                foreach (var key in Facilities)
                {
                    _Facilities += "," + key.ToString();
                }
                _Facilities = _Facilities.Replace("0,", "");
            }
            else
            {
                _Facilities = _Facilities.Replace("0", "");
            }
            //
            string _Features = "0";
            if (Features != null)
            {
                foreach (var key in Features)
                {
                    _Features += "," + key.ToString();
                }
                _Features = _Features.Replace("0,", "");
            }
            else
            {
                _Features = _Features.Replace("0", "");
            }
            //
            ListingService.UpdateStep3(id, _Features, _Facilities);
            Session["messageType"] = "Success";
            Session["message"] = "Updated successfully.";

            return RedirectToAction("Step4/" + id.ToString());

        }
        //
        [HttpPost, ValidateInput(false)]
        public ActionResult Step4(FormCollection form)
        {
            int ListingID = 0;
            if (form["ListingID"].ToString() != "")
            {
                ListingID = Int32.Parse(form["ListingID"].ToString());
                string lat = form["lat"].ToString().Trim();
                string lng = form["lng"].ToString().Trim();
                var listing = new Model.Listings
                {
                    ID = ListingID,
                    Longitude = lng,
                    Latitude = lat
                };
                ListingService.Update(listing);
                ListingService.Save();

                Session["messageType"] = "Success";
                Session["message"] = "Updated successfully.";
            }

            return RedirectToAction("Step5/" + ListingID);
        }
        //
        public ActionResult Step4(int? id)
        {

            if (id != null)
            { //for edit
                var model = ListingService.FindById((int)id);
                ViewData["ListingID"] = id;
                ViewData["Latitude"] = model.Latitude;
                ViewData["Longitude"] = model.Longitude;
                ViewData["StatusID"] = model.StatusFID;
                return View("Step4");
            }
            return RedirectToAction("Index");


        }
        //
        //
        //GET 

        public ActionResult Step5(int? id)
        {
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }
            if (id != null)
            { //for edit
                ViewData["ListingID"] = id;
                ViewData["ImageList"] = ListingMediaService.GetListImage((int)id);
                ViewData["TotalPhoto"] = ListingMediaService.getCountItem();
                var model = ListingService.FindById((int)id);
                ViewData["StatusID"] = model.StatusFID;
                return View("Step5");
            }
            else
            {

                return RedirectToAction("Index");
            }
        }
       /*---------------------------------step 6 -----------------------------------------*/
        //
        //
        public ActionResult Step6(decimal? id, decimal? listingFloorPlan_ID)
        {
            try
            {
                if (id != null)
                { //for edit
                    ViewData["ListingID"] = id;
                    Session["ListingID"] = id;
                    var m = ListingService.FindById((int)id);
                    ViewData["StatusID"] = m.StatusFID;
                    var l = ListingFloorPlanService.FindByListingID_Language(id, 1);
                    ViewData["ProjectFloor"] = l;
                    var prj = ListingFloorPlanService.FindByID_Language(listingFloorPlan_ID, 1);
                    var prj1 = ListingFloorPlanService.FindByID_Language(listingFloorPlan_ID, 2);
                    var model = new Models.ListingFloorPlanModel();
                    model.ListingFloorPlan = prj;
                    model.ListingFloorPlan_Local = prj1;
                    return View("Step6", model);
                }
                else
                {
                    return RedirectToAction("Index");
                }
            }
            catch
            {
                return RedirectToAction("Index");
            }
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Step6(Models.ListingFloorPlanModel model, HttpPostedFileBase floorImg)
        {
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }
            if (floorImg != null)
            {
                BinaryReader b = new BinaryReader(floorImg.InputStream);
                byte[] binData = b.ReadBytes(floorImg.ContentLength);
                Image orig = HelperUtility.byteArrayToImage(binData);
                var imgthumb = HelperUtility.imageToByteArray(HelperUtility.GetThumbImage(orig, 650, orig.Width, orig.Height));
                model.ListingFloorPlan.FloorPlanImg = imgthumb;
            }
            model.ListingFloorPlan.ListingFID = decimal.Parse(Session["ListingID"].ToString());
            if (model.ListingFloorPlan.ListingFloorPlan_ID == null) //insert
            {



                ListingFloorPlanService.Create(model.ListingFloorPlan, model.ListingFloorPlan_Local);
                //                Session["message"] = "Records updated successfully.";
                //                Session["messageType"] = "Success";
                // return View("../Content/Create");
            }
            else //for update
            {


                ListingFloorPlanService.Update(model.ListingFloorPlan, model.ListingFloorPlan_Local);
                //                Session["message"] = "Records updated successfully.";
                //                Session["messageType"] = "Success";
            }
            ShowMessage("Records updated successfully.", "Success");

            return RedirectToAction("Step6/" + Session["ListingID"].ToString());
        }

        public ActionResult DeleteStep6(decimal id)
        {
            if (!checkUserLogin())
            {
                return RedirectToAction("LogIn", "Home", new { area = "" });
            }
            decimal res = ListingFloorPlanService.Deleted(id);
            if (res != -1)
                ShowMessage("Records updated successfully.", "Success");
            else
                ShowMessage("Records updated unsuccessfully.", "Error");

            return RedirectToAction("Step6/" + Session["ListingID"].ToString());
        }
        
        public ActionResult ShowFloorImg(decimal id)
        {

            var imageData = PrjDirFlrPlanService.FindByID_Language(id, 1).FloorPlanImg;
            if (imageData == null)
            {
                //return new FilePathResult("~/Content/Images/NoPhoto.png", "image/png");
                string filePath = Server.MapPath("~/Content/images/no_img_default.png");
                string fileName = Path.GetFileName(filePath);
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                BinaryReader br = new BinaryReader(fs);
                var eximg = br.ReadBytes((Int32)fs.Length);
                return File(eximg, "image/jpg");
            }
            else
            {

                return new FileContentResult(imageData.ToArray(), "image/jpeg");
            }
            //return File( imageData, "image/jpg" );
        }
        void ShowMessage(string msg, string type)
        {
            Session["message"] = msg;
            Session["messageType"] = type;
        }
        public bool checkUserLogin()
        {
            var loginAcc = this.Session[Constants.Session_User] as Model.Admin;
            if (loginAcc == null)
            {
                return false;
            }
            return true;
        }
        /*-------------------------------------------------------end step 6-------------------------------------------------------*/
        
        /**/
        //
        //GET :Property/Delete/id 

        public ActionResult Active(int id)
        {
            try
            {

                ListingService.ChangeStatus(id.ToString(), 1);

                Session["message"] = "Status updated successfully.";
                if (Session["pageindex"] != null)
                {
                    return RedirectToAction("Index/1?page=" + Session["pageindex"].ToString());
                }
                else
                {
                    return RedirectToAction("Index/1");
                }
                
                }
            catch
            {
                return View();
            }
        }
        public ActionResult Draft(int id)
        {
            try
            {

                ListingService.ChangeStatus(id.ToString(), 2);

                Session["message"] = "Status updated successfully.";
                return RedirectToAction("Index/2?page=" + Session["pageindex"].ToString());
            }
            catch
            {
                return View();
            }
        }
        public ActionResult Delete(int id)
        {
            try
            {

                ListingService.ChangeStatus(id.ToString(), 3);

                Session["message"] = "Status updated successfully.";
                return RedirectToAction("Index/3?page=" + Session["pageindex"].ToString());
            }
            catch
            {
                return View();
            }
        }
        //
        // POST//BulkProcess
        //
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult BulkProcess(string id, IEnumerable<int> selected)
        {

            try
            {
                string arr_id = "0";
                foreach (var key in selected)
                {
                    arr_id += "," + key.ToString();
                }
                //
                if (id == "Active")
                {

                    ListingService.ChangeStatus(arr_id, 1);
                    Session["message"] = "Records updated successfully.";
                    return RedirectToAction("Index/1?page=" + Session["pageindex"].ToString());
                }
                //
                if (id == "Draft")
                {
                    ListingService.ChangeStatus(arr_id, 2);
                    Session["message"] = "Records updated successfully.";
                    return RedirectToAction("Index/2?page=" + Session["pageindex"].ToString());
                }
                //
                if (id == "Delete")
                {
                    ListingService.ChangeStatus(arr_id,3);
                    Session["message"] = "Records updated successfully.";
                    return RedirectToAction("Index/3?page=" + Session["pageindex"].ToString());
                }

                return RedirectToAction("Index");
            }
            catch
            {

                return RedirectToAction("Index");
            }
        }





        #region "Image Media"
        public ActionResult RemoveImg(int id)
        {
            try
            {
                var media = ListingMediaService.GetListingMediaById(id);
                if (media != null)
                {
                    ListingMediaService.Delete(media);
                    ListingMediaService.Save();
                    Session["messageType"] = "Success";
                    Session["message"] = "Deleted successfully.";

                    return RedirectToAction("/Step5/" + media.ListingsFID.ToString());
                }
                return View("Step1");
            }
            catch
            {
                return View("Step1");
            }
        }
        public ActionResult ChangeStatusImg(int id)
        {
            try
            {
                var media = ListingMediaService.GetListingMediaById(id);
                if (media.IsActive == true)
                {
                    media.IsActive = false;
                }
                else
                {
                    media.IsActive = true;
                }
                ListingMediaService.Update(media);
                ListingMediaService.Save();
                Session["messageType"] = "Success";
                Session["message"] = "Updated successfully.";
                return RedirectToAction("/Step5/" + media.ListingsFID.ToString());
            }
            catch
            {
                return View("Step1");
            }
        }
        public ActionResult SetDefaultImg(int id)
        {
            try
            {
                var media = ListingMediaService.GetListingMediaById(id);
                if (media.IsDefault == true)
                {
                    media.IsDefault = false;
                }
                else
                {
                    media.IsDefault = true;
                }
                ListingMediaService.Update(media);
                ListingMediaService.Save();
                Session["messageType"] = "Success";
                Session["message"] = "Updated successfully.";
                return RedirectToAction("/Step5/" + media.ListingsFID.ToString());
            }
            catch
            {
                return View("Step1");
            }
        }
        #endregion


        public string SaveOrder(string id)
        {

            string[] arrData = id.Split(',');
            int countnum = arrData.Length;
            for (int i = 0; i < countnum; i++)
            {
                // UpdateOrder(arrData[i],i+1,1);
                // UpdateOrder(arrData[i], i + 1, 2);

            }
            for (int i = 0; i < arrData.Length; i++)
            {
                ListingMediaService.UpdateOrder(decimal.Parse(arrData[i]), i + 1);
            }
            return "OK";
        }
    }
}
